package com.unione.map.view.viewmodel

import android.text.TextUtils
import android.util.Log
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.unione.map.RobotMapApplication
import com.unione.map.constant.AppConstant
import com.unione.unione_network.IReceiveMessage
import com.unione.unione_protocol.robot_auto.bean.RobotInfo
import com.unione.unione_voice.viewmodel.CommonAIVoiceModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MainViewModel : CommonAIVoiceModel(), IReceiveMessage {

    companion object {
        const val TAG = "MainViewModel"

    }

    private var mIsFirstGetMessage = true


    override fun onConnectSuccess() {

    }

    override fun onConnectFailed() {

    }

    override fun onClose() {

    }

    override fun onMessage(text: String?) {
        if (!TextUtils.isEmpty(text)) {
            try {
                Log.d(TAG, text.toString())
                val robotState: RobotInfo = Gson().fromJson(text, RobotInfo::class.java)
                viewModelScope.launch(Dispatchers.Main) {
                    RobotMapApplication.appViewModel.liveDataRobotState.value = robotState
                }
                if (mIsFirstGetMessage) {
                    AppConstant.currentScene = robotState.currentScene
                    mIsFirstGetMessage = !mIsFirstGetMessage
                }
            } catch (e: Exception) {
                Log.d(TAG, e.localizedMessage.toString())
            }
        }
    }


}